﻿<%@ WebHandler Language="C#" Class="Medianamik.Sitemap.SitemapHandler" %>

  using System;
  using System.Web;
  using System.Linq;
  using Medianamik.Core;
  using System.Text;
  using System.Xml;
  using System.Collections.Generic;
  using Medianamik.Core.Urls;

  namespace Medianamik.Sitemap
  {
  public class SitemapHandler: IHttpHandler
  {
  public void ProcessRequest (HttpContext context)
  {
  HttpContext.Current.Response.ContentType = "text/xml";

  XmlTextWriter siteMap = new XmlTextWriter(HttpContext.Current.Response.OutputStream, System.Text.Encoding.UTF8);
  siteMap.Formatting = Formatting.Indented;
  siteMap.WriteStartDocument();
  siteMap.WriteStartElement("urlset");
  siteMap.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
  siteMap.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
  siteMap.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

  var urlDictionary = new ObjectFactory<IUrlDictionary>().Get();
            
            var authority = context.Request.Url.GetLeftPart(UriPartial.Authority).ToString();
            
            urlDictionary
                .GetAllEntries(IndexationModes.Indexed)
                .Where(u => u.Generation > -1)
                .Select(url => url.RequestedUrl.ToString())
                .Where(url => url.StartsWith(authority, StringComparison.OrdinalIgnoreCase))
                .Distinct().ForEach(url =>
                {
                    siteMap.WriteStartElement("url");
                    siteMap.WriteElementString("loc", url.ToString());
                    siteMap.WriteEndElement();
                });

            siteMap.WriteEndElement();
            siteMap.Close();
        }

        public bool IsReusable {
            get {return false;}
        }
    }
}